package com.xh.bussiness.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.io.Files;
import com.xh.bussiness.system.model.FileList;
import com.xh.bussiness.tiku.bean.dto.*;
import com.xh.bussiness.tiku.bean.request.*;
import com.xh.bussiness.tiku.constant.PaperConstant;
import com.xh.bussiness.tiku.dao.KnowledgeMapper;
import com.xh.bussiness.tiku.dao.PaperChapterMapper;
import com.xh.bussiness.tiku.dao.PaperMapper;
import com.xh.bussiness.tiku.dao.PaperQuestionMapper;
import com.xh.bussiness.tiku.model.*;
import com.xh.bussiness.tiku.service.*;
import com.xh.bussiness.weixin.service.IWeixinService;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.properties.XhProperties;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.ObjectUtils;
import com.xh.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 试卷表 服务实现类
 * </p>
 *
 * @author daiwei
 * @since 2019-01-14
 */
@Service
public class PaperServiceImpl extends BaseServiceImpl<PaperMapper, Paper> implements IPaperService {

    public static final Logger log = LoggerFactory.getLogger(PaperServiceImpl.class);

    @Autowired
    private XhProperties xhProperties;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private PaperChapterMapper paperChapterMapper;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    @Autowired
    private KnowledgeMapper knowledgeMapper;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuestionTypeRelationService questionTypeRelationService;
    @Autowired
    private IQuestionImportLogService questionImportLogService;
    @Autowired
    private IPaperQuestionService paperQuestionService;
    @Autowired
    private IWeixinService weixinService;

    @Override
    public List<PaperModuleDto> queryPaperModule() {
        return this.selectList(null, PaperModuleDto.class);
    }

    @Override
    public XhPage queryPaperPage(XhPage page, PaperQueryRequest bean) {
        QueryWrapper<Paper> qw = new QueryWrapper<Paper>();
        qw.and(wrapper -> wrapper.gt("status",-1).or().isNull("status"));
        //拼装条件
        qw = prepareParams(bean, qw);
        if (bean.getCheckStatus() != null) {
            qw.eq("check_status", bean.getCheckStatus());
        }
        if (!StringUtils.isEmpty(bean.getGradeRangeId())) {
            qw.eq("grade_range", bean.getGradeRangeId());
        }
        if (!StringUtils.isEmpty(bean.getSubjectId())) {
            qw.eq("subject_id", bean.getSubjectId());
        }
        if (!StringUtils.isEmpty(bean.getYear())) {
            qw.eq("year", bean.getYear());
        }
        if (bean.getIsEntranceTest() == null) {
            if (!CollectionUtils.isEmpty(bean.getYears())) {
                qw.and(wrapper -> wrapper.in("year", bean.getYears()).or().isNull("year"));
            }
        }
        // 查询个人组卷
        if (bean.getType() != null && bean.getType() == 2) {
            qw.eq("creator_id", bean.getCreatorId());
            qw.eq("is_public", 0);
        }
        if (bean.getType() != null && bean.getType() == 1) {
            qw.eq("is_public", 1);
        }
        if (!StringUtils.isEmpty(bean.getProvinceId())) {
            qw.eq("province_id", bean.getProvinceId());
        }
        if (!StringUtils.isEmpty(bean.getCityId())) {
            qw.eq("city_id", bean.getCityId());
        }
        if (!StringUtils.isEmpty(bean.getCounty())) {
            qw.eq("county", bean.getCounty());
        }
        if (!StringUtils.isEmpty(bean.getLongwenCityId())) {
            qw.eq("longwen_city_id", bean.getLongwenCityId());
        }
        if (!StringUtils.isEmpty(bean.getSource())) {
            qw.eq("source", bean.getSource());
        }
        if (!StringUtils.isEmpty(bean.getGradeId())) {
            qw.eq("grade_id", bean.getGradeId());
        }
        if (!CollectionUtils.isEmpty(bean.getGradeIds())) {
            qw.and(wrapper -> wrapper.in("grade_id", bean.getGradeIds()).or().isNull("grade_id"));
        }
        if (!StringUtils.isEmpty(bean.getTitle())) {
            qw.like("title", bean.getTitle());
        }
        if (bean.getNeSourceFrom() != null) {
            qw.ne("source_from", bean.getNeSourceFrom());
        }
        if (bean.getIsEntranceTest() != null) {
            qw.eq("is_entrance_test", bean.getIsEntranceTest());
        }else{
            qw.and(wrapper -> wrapper.eq("is_entrance_test",0).or().isNull("is_entrance_test"));
            qw.and(wrapper -> wrapper.eq("is_exercise",0).or().isNull("is_exercise"));
            //没有试卷类型时，分别查询公共试卷和个人试卷
            if (bean.getType() == null) {
                qw.and(wrapper -> wrapper.eq("is_public", 1).or().eq("creator_id", bean.getCreatorId()));
            }
        }

        qw.orderByDesc("create_time");
        XhPage xhPage = (XhPage) this.selectPage(page, qw, PaperDto.class);
        return xhPage;
    }


    @Override
    public List queryPaper(PaperQueryRequest bean) {
        QueryWrapper qw = new QueryWrapper<Paper>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return this.selectList(qw, PaperDto.class);
    }

    @Override
    public PaperDto addPaper(HttpServletRequest request,PaperSaveRequest bean) {
        Paper paper;
        if (StringUtils.isEmpty(bean.getId())) {
            paper = new Paper();
            paper.init();
            BeanUtils.copyProperties(bean, paper);
            //默认显示标题
            paper.setShowTitle(1);
            paper.setShowSideTitle(1);
            boolean paperSaveFlag = this.insert(paper);
            if (!paperSaveFlag) {
                throw new XhException("试卷保存失败");
            }
        } else {
            paper = this.dao.selectById(bean.getId());
            bean.setIsPublic(paper.getIsPublic());
            BeanUtils.copyProperties(bean, paper);
            if (paper.getIsEntranceTest().equals(1) && bean.getStatus() > -1) {
                //生成微信小程序二维码
                String qrCodeUrl = weixinService.wxaCode(request, weixinService.getWeixinToken(), "pages/common/QRCode/index", paper.getId());
                paper.setQrCodeUrl(qrCodeUrl);
                paper.setAnswerCount(0);
            }
            this.update(paper);
            //维护试题引用数
            List<String> questionIds = paperQuestionMapper.queryQuestionIdByPaperId(paper.getId());
            if (!CollectionUtils.isEmpty(questionIds)) {
                questionService.batchModifyQuestionUseCount(questionIds, 2);
            }
            //删除试卷内容重新添加
            paperChapterMapper.deleteByPaperId(paper.getId());
            paperQuestionMapper.deleteByPaperId(paper.getId());
        }

        //用于保存箐优网试题
        //Map<String, List<String>> qyQuestionIdMap = new HashMap<>();
        //Map<String, String> duplicateQuesIdMapValid = new HashMap<>();
        List<String> questionList = new ArrayList<>();
        Integer paperScore = 0;
        if (!CollectionUtils.isEmpty(bean.getPaperChapters())) {//章节体系
            paper.setChapterCount(bean.getPaperChapters().size());
            Integer questionCount = 0;
            for (int i = 0; i < bean.getPaperChapters().size(); i++) {//保存章节
                PaperChapterSaveRequest chapterSaveRequest = bean.getPaperChapters().get(i);
                PaperChapter paperChapter = new PaperChapter();
                paperChapter.init();
                paperChapter.setTitle(chapterSaveRequest.getTitle());
                paperChapter.setOrderNo(i + 1);
                paperChapter.setPaperId(paper.getId());
                paperChapter.setQuestionCount(chapterSaveRequest.getQuestions().size());

                paperChapterMapper.insert(paperChapter);

                if (!CollectionUtils.isEmpty(chapterSaveRequest.getQuestions())) {
                    for (int j = 0; j < chapterSaveRequest.getQuestions().size(); j++) {//保存章节试题
                        PaperQuestionSaveRequest paperQuestionBean = chapterSaveRequest.getQuestions().get(j);
                        PaperQuestion paperQuestion = new PaperQuestion();
                        paperQuestion.setPaperId(paper.getId());
                        paperQuestion.setPaperChapterId(paperChapter.getId());
                        paperQuestion.setOrderNo(j + 1);
                        paperQuestion.setQuestionId(paperQuestionBean.getQuestionId());
                        paperQuestion.setScore(paperQuestionBean.getScore());
                        paperQuestion.setBlankRowCount(paperQuestionBean.getBlankRowCount());
                        paperQuestionMapper.insert(paperQuestion);

                        paperChapter.setTotalScore(paperQuestion.getScore() + paperChapter.getTotalScore());

                        questionList.add(paperQuestionBean.getQuestionId());

                        paperScore += paperQuestionBean.getScore();
                    }
                }
                questionCount += CollectionUtils.isEmpty(chapterSaveRequest.getQuestions()) ? 0 : chapterSaveRequest.getQuestions().size();
                paper.setTotalScore(paperChapter.getTotalScore() + paper.getTotalScore());
                paperChapterMapper.updateById(paperChapter);
            }
            paper.setChapterCount(bean.getPaperChapters().size());
            paper.setQuestionCount(questionCount);
            paper.setTotalScore(paperScore);
        } else if (!CollectionUtils.isEmpty(bean.getQuestions())) {//不分章节
            for (int i = 0; i < bean.getQuestions().size(); i++) {
                PaperQuestionSaveRequest paperQuestionBean = bean.getQuestions().get(i);
                PaperQuestion paperQuestion = new PaperQuestion();
                paperQuestion.setPaperId(paper.getId());
                paperQuestion.setOrderNo(i + 1);
                paperQuestion.setQuestionId(paperQuestionBean.getQuestionId());
                paperQuestion.setScore(paperQuestionBean.getScore());
                paperQuestion.setBlankRowCount(paperQuestionBean.getBlankRowCount());
                paperQuestionMapper.insert(paperQuestion);
                paper.setTotalScore(paperQuestion.getScore() + (paper.getTotalScore() == null ? 0 : paper.getTotalScore()));

                //插入试题id
                //saveQuestion(qyQuestionIdMap, duplicateQuesIdMapValid, paperQuestionBean);

                questionList.add(paperQuestionBean.getQuestionId());

                paperScore += paperQuestionBean.getScore();
            }
            paper.setQuestionCount(bean.getQuestions().size());
            paper.setTotalScore(paperScore);
        } else {
            // 可以建没有试题的试卷
            /*if(paper.getSourceFrom() < 3){
                throw new XhException("保存数据至少需要包含1道试题");
            }*/
        }
        this.update(paper);
        //试题引用数维护
        questionService.batchModifyQuestionUseCount(questionList, 1);

        //同步箐优网试题到本地
//        try {
//            if (!MapUtils.isEmpty(qyQuestionIdMap)) {
//                for (String subject : qyQuestionIdMap.keySet()) {
//                    questionService.queryFromJY(subject, qyQuestionIdMap.get(subject));
//                }
//            }
//        } catch (Exception e) {
//            log.error("保存备课同步试题异常：" + e.getMessage());
//        }

        return getPaper(paper.getId());
    }

    @Override
    public void batchSavePaper(PaperBatchSaveRequest bean) {
        List<FileList> papers = bean.getPapers();
        if (papers.isEmpty()) {
            return;
        }
        if(bean.getIsExercise() != null && 1 == bean.getIsExercise()){
            bean.setStandardExercise(1);
        }
        for (FileList item : papers) {
            Paper paper = new Paper();
            paper.init();
            paper.setTitle(Files.getNameWithoutExtension(item.getOriFilename()));
            paper.setFilePath(item.getFilePath());
            BeanUtils.copyProperties(bean, paper);
            this.insert(paper);
        }
    }

    /*private void saveQuestion(Map<String, List<String>> qyQuestionIdMap, Map<String, String> duplicateQuesIdMapValid, PaperQuestionSaveRequest paperQuestionBean) {
        //插入试题id
        if (!StringUtils.isEmpty(paperQuestionBean.getQuestionId())
                && !StringUtils.isEmpty(paperQuestionBean.getSubjectId())) {
            List<String> quesIds;
            if (qyQuestionIdMap.containsKey(paperQuestionBean.getSubjectId()) && !duplicateQuesIdMapValid.containsKey(paperQuestionBean.getQuestionId())) {
                quesIds = qyQuestionIdMap.get(paperQuestionBean.getSubjectId());
                quesIds.add(paperQuestionBean.getQuestionId());
                qyQuestionIdMap.put(paperQuestionBean.getSubjectId(), quesIds);
            } else if (!duplicateQuesIdMapValid.containsKey(paperQuestionBean.getQuestionId())) {
                quesIds = new ArrayList<>();
                quesIds.add(paperQuestionBean.getQuestionId());
                qyQuestionIdMap.put(paperQuestionBean.getSubjectId(), quesIds);
            }
        }
    }*/

    @Override
    public PaperDto getPaper(String id) {
        Paper paper = this.getById(id);
        PaperDto paperBean = new PaperDto();
        if (paper==null){
            return null;
        }
        ObjectUtils.copyNonNullProperties(paper, paperBean);

        if (paper.getSourceFrom() == 3) {
            return paperBean;
        }
        if (paperBean.getChapterCount() != null && paperBean.getChapterCount() > 0) {
            paperBean.setPaperCharpts(new ArrayList<>());
            //获取章节
            QueryWrapper pcQw = new QueryWrapper();
            pcQw.eq("paper_id", id);
            pcQw.orderByAsc("order_no");
            List<PaperChapter> paperChapterList = paperChapterMapper.selectList(pcQw);
            for (PaperChapter pc : paperChapterList) {
                PaperChapterDto paperChapterDto = new PaperChapterDto();
                ObjectUtils.copyNonNullProperties(pc, paperChapterDto);
                paperChapterDto.setAvgScore(0);
                //获取试题集合
                QueryWrapper pcqQw = new QueryWrapper();
                pcqQw.eq("paper_chapter_id", pc.getId());
                pcqQw.orderByAsc("order_no");
                List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
                paperChapterDto.setQuestions(new ArrayList<>());
                for (PaperQuestion pq : paperQuestionList) {
                    PaperQuestionDto paperQuestionDto = new PaperQuestionDto();
                    ObjectUtils.copyNonNullProperties(pq, paperQuestionDto);
                    paperQuestionDto.setQuestion(questionService.getQuestion(paperQuestionDto.getQuestionId(), null, true, true, false, false,false));
                    paperChapterDto.getQuestions().add(paperQuestionDto);
                }
                if (StringUtils.isEmpty(paperChapterDto.getTitle()) && !CollectionUtils.isEmpty(paperChapterDto.getQuestions())) {
                    paperChapterDto.setTitle(paperChapterDto.getQuestions().get(0).getQuestion().getBasicQuestionTypeName());
                }
                if (paperChapterDto.getChapterQuestionType() == null && !CollectionUtils.isEmpty(paperChapterDto.getQuestions())) {
                    paperChapterDto.setChapterQuestionType(paperChapterDto.getQuestions().get(0).getQuestion().getBasicQuestionType());
                }
                paperBean.getPaperCharpts().add(paperChapterDto);
            }
        } else {
            //获取试题
            QueryWrapper pcqQw = new QueryWrapper();
            pcqQw.eq("paper_id", paperBean.getId());
            pcqQw.orderByAsc("order_no");
            List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
            paperBean.setQuestions(new ArrayList<>());
            for (PaperQuestion pq : paperQuestionList) {
                PaperQuestionDto paperQuestionDto = new PaperQuestionDto();
                ObjectUtils.copyNonNullProperties(pq, paperQuestionDto);
                paperQuestionDto.setQuestion(questionService.getQuestion(paperQuestionDto.getQuestionId(), null));
                paperBean.getQuestions().add(paperQuestionDto);
            }
            paperBean.setPaperCharpts(new ArrayList<>());
        }

        return paperBean;
    }

    /**
     * 获取发布为作业的试卷中的试题(被删除的试题也要展示)
     * @author 赵文博
     * @date 2021/5/8 15:36
     * @param paperId
     * @return com.xh.bussiness.tiku.bean.dto.PaperDto
     **/
    @Override
    public PaperDto getPracticePaper(String paperId){
        Paper paper = this.getById(paperId);
        PaperDto paperBean = new PaperDto();
        ObjectUtils.copyNonNullProperties(paper, paperBean);

        if (paper.getSourceFrom() == 3) {
            return paperBean;
        }
        if (paperBean.getChapterCount() != null && paperBean.getChapterCount() > 0) {
            paperBean.setPaperCharpts(new ArrayList<>());
            //获取章节
            QueryWrapper pcQw = new QueryWrapper();
            pcQw.eq("paper_id", paperId);
            pcQw.orderByAsc("order_no");
            List<PaperChapter> paperChapterList = paperChapterMapper.selectList(pcQw);
            for (PaperChapter pc : paperChapterList) {
                PaperChapterDto paperChapterDto = new PaperChapterDto();
                ObjectUtils.copyNonNullProperties(pc, paperChapterDto);
                paperChapterDto.setAvgScore(0);
                //获取试题集合
                QueryWrapper pcqQw = new QueryWrapper();
                pcqQw.eq("paper_chapter_id", pc.getId());
                pcqQw.orderByAsc("order_no");
                List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
                paperChapterDto.setQuestions(new ArrayList<>());
                for (PaperQuestion pq : paperQuestionList) {
                    PaperQuestionDto paperQuestionDto = new PaperQuestionDto();
                    ObjectUtils.copyNonNullProperties(pq, paperQuestionDto);
                    paperQuestionDto.setQuestion(questionService.getPracticeQuestion(paperQuestionDto.getQuestionId(), null, true, false, false, false,false));
                    paperChapterDto.getQuestions().add(paperQuestionDto);
                }
                if (StringUtils.isEmpty(paperChapterDto.getTitle()) && !CollectionUtils.isEmpty(paperChapterDto.getQuestions())) {
                    paperChapterDto.setTitle(paperChapterDto.getQuestions().get(0).getQuestion().getBasicQuestionTypeName());
                }
                paperBean.getPaperCharpts().add(paperChapterDto);
            }
        } else {
            //获取试题
            QueryWrapper pcqQw = new QueryWrapper();
            pcqQw.eq("paper_id", paperBean.getId());
            pcqQw.orderByAsc("order_no");
            List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
            paperBean.setQuestions(new ArrayList<>());
            for (PaperQuestion pq : paperQuestionList) {
                PaperQuestionDto paperQuestionDto = new PaperQuestionDto();
                ObjectUtils.copyNonNullProperties(pq, paperQuestionDto);
                paperQuestionDto.setQuestion(questionService.getPracticeQuestion(paperQuestionDto.getQuestionId(), null));
                paperBean.getQuestions().add(paperQuestionDto);
            }
            paperBean.setPaperCharpts(new ArrayList<>());
        }

        return paperBean;
    }

    @Override
    public PaperDto getSimplePaper(String id) {
        Paper paper = this.getById(id);
        PaperDto paperBean = new PaperDto();
        ObjectUtils.copyNonNullProperties(paper, paperBean);
        return paperBean;
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(PaperQueryRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        return qw;
    }

    @Override
    public boolean checkPaper(String id, Integer status, String rejectReason, String rejectDesc) {
        Paper paper = new Paper();
        paper.setId(id);
        paper.setRejectReason(rejectReason);
        paper.setRejectDesc(rejectDesc);
        paper.setCheckStatus(status);
        return super.update(paper);
    }

    /**
     * 修改试卷属性
     * @author 赵文博
     * @date 2021/5/24 14:26
     * @return boolean
     **/
    @Override
    public boolean updatePaper(Paper paper) {
        if(StringUtils.isNotEmpty(paper.getId())){
            Paper oldPaper = this.getById(paper.getId());
            paper.setIsPublic(oldPaper.getIsPublic());
            paper.setCheckStatus(oldPaper.getCheckStatus());
            return this.update(paper);
        }
        return false;
    }

    @Override
    public XhPage<Paper> queryCheckPaper(XhPage<Paper> page, PaperRequest request) {
        List<Paper> list = this.dao.queryCheckPaper(page, request);
        Long total = this.dao.queryCheckPaperCount(request);
        page.setRecords(list);
        page.setTotal(total);
        return page;
    }

    @Override
    public PaperDto intellectPaper(PaperQuestionRequest bean) throws Exception {
        // 可以建没有试题的试卷
//        if(CollectionUtils.isEmpty(bean.getQuestionType())){
//            throw new Exception("未选择题目类型！");
//        }

        if (bean.getPaperType().equals(PaperConstant.PAPER_AREA.LINK) && !CollectionUtils.isEmpty(bean.getKnowledgeIds())) {
            QueryWrapper<Knowledge> qw = new QueryWrapper();
            qw.in("parent_id", bean.getKnowledgeIds());
            List<Knowledge> knowledges = knowledgeMapper.selectList(qw);
            List<String> ids = knowledges.stream().map(Knowledge::getId).collect(Collectors.toList());
            bean.setKnowledgeIds(ids);
        }

        List<PaperChapterSaveRequest> questions = new ArrayList<>();
        PaperSaveRequest paper = new PaperSaveRequest();
        paper.setFormat(bean.getFormat());
        paper.setTitle(bean.getTitle());
        paper.setGradeRange(bean.getGradeRange());
        paper.setSubjectId(bean.getSubjectId());
        paper.setGradeId(bean.getGradeId());
        paper.setSource(bean.getSource());
        paper.setYear(bean.getYear());
        paper.setSourceFrom(bean.getSourceFrom());
        paper.setIsPublic(bean.getIsPublic());

        for (int i = 0; i < bean.getQuestionType().size(); i++) {
            Integer questionType = bean.getQuestionType().get(i);
            Integer score = bean.getQuestionScore().get(i);
            Integer size = bean.getQuestionCount().get(i);
            QuestionQueryRequest qqr = new QuestionQueryRequest();
            qqr.setSubject(bean.getSubjectId());
            qqr.setType(questionType);
            qqr.setDifficult(bean.getDifficult());
            qqr.setKnowledgePoints(bean.getKnowledgeIds());
            qqr.setRandomStart(0);
            qqr.setRandomCount(size);
            List<String> questionList = questionService.queryQuesitonRandom(qqr);
            if (questionList.size() > 0) {
                qqr.setIds(questionList.toArray(new String[0]));
                List queryQuestion = questionService.queryQuestion(qqr);
                PaperChapterSaveRequest chapterSaveRequest = new PaperChapterSaveRequest();
                chapterSaveRequest.setOrderNo(i + 1);
                chapterSaveRequest.setQuestionCount(queryQuestion.size());
                chapterSaveRequest.setTotalScore(queryQuestion.size() * score);
                QuestionTypeRelation questionTypeRelation = questionTypeRelationService.queryByJyQuestionType(bean.getSubjectId(), Integer.valueOf(questionType));
                chapterSaveRequest.setTitle(questionTypeRelation.getJyQuestionTypeName());
                List<PaperQuestionSaveRequest> paperSaveRequests = new ArrayList<>();
                for (Object question : queryQuestion) {
                    QuestionDto dto = (QuestionDto) question;
                    PaperQuestionSaveRequest pqsr = new PaperQuestionSaveRequest();
                    pqsr.setQuestionId(dto.getId());
                    pqsr.setSubjectId(dto.getSubjectId());
                    pqsr.setScore(score);
                    paperSaveRequests.add(pqsr);

                }
                chapterSaveRequest.setQuestions(paperSaveRequests);
                questions.add(chapterSaveRequest);
            }
        }
        paper.setPaperChapters(questions);
        paper.setTotalScore(0);
        paper.setQuestionCount(0);
//        return null;
        return addPaper(null,paper);
    }

    @Override
    public void deletePaper(String paperId) {
        questionImportLogService.removeLogPaperByPaperId(paperId);

        this.delete(paperId);

        List<String> questionIds = paperQuestionMapper.queryQuestionIdByPaperId(paperId);
        if (!CollectionUtils.isEmpty(questionIds)) {
            questionService.batchModifyQuestionUseCount(questionIds, 2);
        }
    }

    @Override
    public PaperQuestion addBlankRow(String paperId, String questionId, Integer blankRowCount) {
        QueryWrapper<PaperQuestion> qw = new QueryWrapper();
        qw.eq("paper_id", paperId);
        qw.eq("question_id", questionId);
        PaperQuestion paperQuestion = paperQuestionService.selectFirst(qw);
        paperQuestion.setBlankRowCount(blankRowCount);
        paperQuestionService.update(paperQuestion);
        return paperQuestion;
    }

    @Override
    public Integer queryPaperScore(String id) {
        PaperQuestionRequest request = new PaperQuestionRequest();
        request.setPaperId(id);

        List<PaperQuestion> list = paperQuestionService.queryPaperQuestion(request);
        if (!CollectionUtils.isEmpty(list)) {
            return list.stream().mapToInt(PaperQuestion::getScore).sum();
        }
        return 0;
    }

    @Override
    public void addPaperQuestion(String businessType,String paperId, List<String> questionIds) {
        if (StringUtils.isEmpty(paperId) || CollectionUtils.isEmpty(questionIds)) {
            return;
        }
        Paper paper = this.getById(paperId);
        if (paper == null) {
            paper = new Paper();
            paper.setId(paperId);
            paper.setStatus(-1);
            paper.insert();
        }
        if (businessType.equals("entranceTest")) {
            paper.setIsEntranceTest(1);
        }
        QuestionQueryRequest questionQueryRequest = new QuestionQueryRequest();
        questionQueryRequest.setIds(questionIds.toArray(new String[]{}));

        List<QuestionDto> list = questionService.queryQuestion(questionQueryRequest);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Map<Integer, List<QuestionDto>> groupQuestionTypeMap = list.stream().collect(Collectors.groupingBy(QuestionDto::getType));
        List<Integer> types = list.stream().map(QuestionDto::getType).distinct().sorted().collect(Collectors.toList());

        for (int j = 0; j < types.size(); j++) {
            Integer type = types.get(j);
            paper.setChapterCount(types.size());
            List<QuestionDto> questionDtos = groupQuestionTypeMap.get(type);
            if (!CollectionUtils.isEmpty(questionDtos)) {
                //试卷章节
                PaperChapter paperChapter = new PaperChapter();
                paperChapter.init();
                paperChapter.setTitle( questionDtos.get(0).getQuestionTypeName());
                paperChapter.setOrderNo(j + 1);
                paperChapter.setPaperId(paper.getId());
                paperChapter.setQuestionCount(questionDtos.size());
                paperChapterMapper.insert(paperChapter);

                for (int i = 0; i < questionDtos.size(); i++) {
                    QuestionDto questionDto = questionDtos.get(i);
                    PaperQuestion paperQuestion = new PaperQuestion();
                    paperQuestion.setPaperId(paper.getId());
                    paperQuestion.setPaperChapterId(paperChapter.getId());
                    paperQuestion.setOrderNo(i + 1);
                    paperQuestion.setQuestionId(questionDto.getId());
                    paperQuestion.setScore(0);
                    paperQuestion.setBlankRowCount(0);
                    paperQuestionMapper.insert(paperQuestion);
                }
            }
        }
        paper.setQuestionCount(questionIds.size());
        paper.setChapterCount(types.size());
        paper.setTotalScore(0);
        paper.setSourceFrom(5);
        this.update(paper);
        //试题引用数维护
        questionService.batchModifyQuestionUseCount(questionIds, 1);
    }

    @Override
    public String copyPaper(String paperId) {
        Paper paper = this.getById(paperId);
        if (null == paper) return null;
        paper.setId(null);
        this.insert(paper);
        String newId = paper.getId();
        if (paper.getChapterCount() != null && paper.getChapterCount() > 0) {
            //获取章节
            QueryWrapper pcQw = new QueryWrapper();
            pcQw.eq("paper_id", paperId);
            pcQw.orderByAsc("order_no");
            List<PaperChapter> paperChapterList = paperChapterMapper.selectList(pcQw);
            for (int i = 0; i < paperChapterList.size(); i++) {
                PaperChapter paperChapter = paperChapterList.get(i);
                String paperChapterId = paperChapter.getId();
                paperChapter.setOrderNo(i+1);
                paperChapter.setPaperId(newId);
                paperChapter.setId(null);
                paperChapterMapper.insert(paperChapter);
                String newPaperChapterId = paperChapter.getId();

                //获取试题集合
                QueryWrapper pcqQw = new QueryWrapper();
                pcqQw.eq("paper_chapter_id", paperChapterId);
                pcqQw.orderByAsc("order_no");
                List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
                for (int j = 0; j < paperQuestionList.size(); j++) {
                    PaperQuestion paperQuestion = paperQuestionList.get(j);
                    paperQuestion.setPaperId(newId);
                    paperQuestion.setPaperChapterId(newPaperChapterId);
                    paperQuestion.setOrderNo(j+1);
                    paperQuestion.setId(null);
                    paperQuestionMapper.insert(paperQuestion);
                }
            }

        } else {
            //获取试题
            QueryWrapper pcqQw = new QueryWrapper();
            pcqQw.eq("paper_id", paperId);
            pcqQw.orderByAsc("order_no");
            List<PaperQuestion> paperQuestionList = paperQuestionMapper.selectList(pcqQw);
            for (int j = 0; j < paperQuestionList.size(); j++) {
                PaperQuestion paperQuestion = paperQuestionList.get(j);
                paperQuestion.setPaperId(newId);
                paperQuestion.setOrderNo(j+1);
                paperQuestion.setId(null);
                paperQuestionMapper.insert(paperQuestion);
            }
        }
         return newId;
    }

    @Override
    public XhPage<PaperQueryRequest> queryExercise(XhPage<Paper> page, PaperQueryRequest bean) {
        return this.dao.queryExercise(page,bean);
    }

    @Override
    public XhPage<PaperQueryRequest> queryEntranceTest(XhPage<Paper> page, PaperQueryRequest bean) {
        return this.dao.queryEntranceTest(page,bean);
    }

    @Override
    public void updateAnswerCount(String id) {
        this.dao.updateAnswerCount(id);
    }

    @Override
    public List<String> selectPaperQuestion(String paperId) {
        return this.dao.selectPaperQuestion(paperId);
    }

    @Override
    public Integer selectScoreSum(List<String> ids) {
        return this.dao.selectScoreSum(ids);
    }
}
